package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.IUserService;
import com.itheima.reggie.utils.SMSUtils2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;


    @PostMapping("/sendMsg")
    public R semdMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = RandomUtil.randomNumbers(4).toString();
            log.info("code={}", code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils2.sendSms(phone, code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone, code);

            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        log.info("login");
        String phone = map.get("phone");
        String code = map.get("code");
        //验证
        Object codeInSession = session.getAttribute(phone);
        System.out.println(codeInSession);

        //确定有缓存
        if (codeInSession != null && codeInSession.equals(code)) {
            //放行

            //如果是新用户自动注册
            //先根据phone查询
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone, phone);
            User userLogin = userService.getOne(qw);
            if (userLogin == null) {
                //新用户,注册
                User user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }


            //存入session
            session.setAttribute("user", userLogin);

            return R.success("登录成功");
        }
        return R.error("登录失败");


    }


    @PostMapping("/loginout")
    public R loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
